package netTrackerGUI;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netTracker.NetTracker;
import netTracker.Util;
import netTracker.network.Address;

@SuppressWarnings("serial")	// Panel does not need to be serializable.

public class MenuPanel extends JPanel implements ActionListener{
	
	final static int DEFAULT_PORT = 4000;
	
	/** Utility class with debug flag: */
	Util util = new Util(this, true);
	
	/** The netTracker for which this menu panel operates. */
	NetTracker netTracker;
	/** A JList of servers. */
	JList serverList;
	/** An array of servers for the server list. */
	Address[] serverNames;
	JTextArea portChoice;
	
	/**
	 * Constructs a menu panel.
	 * @param netTracker the tracker for which the menu is operating.
	 */
	public MenuPanel(NetTracker netTracker){
		super();			// Call JPanel constructor
		this.netTracker = netTracker;
		setLayout(new GridLayout(4,0));
		
		/** Panels for different menu sections: */
		JPanel connectionPanel = new JPanel();
		JPanel serverListPanel = new JPanel();
		JPanel optionsPanel = new JPanel();
		JPanel playPanel = new JPanel();
	
		/** Add buttons for connecting: */
		portChoice = new JTextArea(""+DEFAULT_PORT, 1, 6);
		JButton connect = new JButton("Connect");
		connect.addActionListener(this);
		JButton startServer = new JButton("Start Server");
		startServer.addActionListener(this);
		
		connectionPanel.add(portChoice);
		connectionPanel.add(connect);
		connectionPanel.add(startServer);
		
		/** Add list for server list:  */
		/** Initialize server names. */
		serverNames = new Address[NetTracker.MAX_SERVERS];
		for(int i=0; i<serverNames.length; i++)
			serverNames[i] = new Address();
		serverList = new JList(serverNames);
		new JScrollPane(serverList);	// Add scroll pane
		serverList.setFixedCellHeight(13);
        serverList.setFixedCellWidth(200);
		JButton listServersButton = new JButton("List Servers");
		JButton joinServerButton = new JButton("Join Server");
		listServersButton.addActionListener(this);
		joinServerButton.addActionListener(this);

		serverListPanel.add(serverList);
		serverListPanel.add(listServersButton);
		serverListPanel.add(joinServerButton);
		
		
		/** Add radio buttons for locking: */
		JRadioButton lockingOn = new JRadioButton("Locking On");
		JRadioButton lockingOff = new JRadioButton("Locking Off");
		lockingOn.setActionCommand("Locking On");
		lockingOn.setSelected(true);
		lockingOn.addActionListener(this);
		lockingOff.setActionCommand("Locking Off");
		lockingOff.addActionListener(this);
		optionsPanel.add(lockingOn);
		optionsPanel.add(lockingOff);
		ButtonGroup group = new ButtonGroup();
		group.add(lockingOn);
		group.add(lockingOff);

		/** Add play/stop button: */
		JButton play = new JButton ("Play");
		JButton stop = new JButton ("Stop");
		JButton clear = new JButton ("Clear");
		play.addActionListener(this);
		stop.addActionListener(this);
		clear.addActionListener(this);
		playPanel.add(play);
		playPanel.add(stop);
		playPanel.add(clear);
		
		add(connectionPanel);
		add(serverListPanel);
		add(optionsPanel);
		add(playPanel);
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("Start Server")){	
			netTracker.becomeServer();
		}else if (e.getActionCommand().equals("Connect")){
			new Thread(new Connector()).start();
		}else if(e.getActionCommand().equals("List Servers")){
			try{
				addServerNames(netTracker.getServerList());
				serverList.repaint();
			}catch(Exception x){
				System.err.println("Error getting server list.");
				util.debug(x);
			}
		}else if(e.getActionCommand().equals("Join Server")){
			netTracker.joinServer((Address)serverList.getSelectedValue());
		}else if(e.getActionCommand().equals("Locking On")){
			netTracker.setLocking(true);
		}else if (e.getActionCommand().equals("Locking Off")){
			netTracker.setLocking(false);
		}else if (e.getActionCommand().equals("Play")){
			netTracker.play();
		}else if (e.getActionCommand().equals("Stop")){
			netTracker.stop();
		}else if (e.getActionCommand().equals("Clear")){
			netTracker.clearCurrentPattern();
		}
		// Reset focus back to tracker:
		netTracker.getGUI().getTrackerPanel().requestFocusInWindow();
	}
	
	private int findPortChoice() {
		int result = DEFAULT_PORT;
		try{
			result = Integer.parseInt(portChoice.getText());
		}catch(NumberFormatException e){
			System.err.println("Invalid number! "+e);
		}
		return result;
	}

	public void addServerNames(Address[] newNames){
		if(newNames==null)
			return;
		for(int i=0; i<serverNames.length; i++){
			if (i < newNames.length)
				serverNames[i] = newNames[i];
			else
				serverNames[i] = new Address();
		}
	}
	
	/** Override size methods to ensure a correct panel size: */
    public Dimension getMinimumSize()
    { return new Dimension(20,NetTrackerGUI.HEIGHT); }
    public Dimension getMaximumSize()
    { return getMinimumSize(); }
    public Dimension getPreferredSize()
    { return getMinimumSize(); }
    
    /**
     * Small internal class spawned when user presses the connect button.
     * Connects to the NameServer.
     * @author David Cummings
     */
    private class Connector implements Runnable{
		public void run() {
			netTracker.connect(findPortChoice());
		}
    }
}
